<template>
  <div id="InfoList">
    <Info ref="InfoRef" type="warn" :infoData="infoData" :Seriesset="Seriesset" @switchChg="switchChg" />
  </div>
</template>
<script setup>
import Info from '../components/Info.vue'
import Warn from '@/utils/warn'
import Device from '@/utils/device'
import { reactive, ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { provide } from 'vue'
const router = useRouter()
const route = useRoute()
const infoId = ref('')
const times = ref([])
const start = ref(null)
const end = ref(null)
const InfoRef = ref()
const infoData = ref({})

async function getInfoList(status) {
  let res = await Warn.getWarnInfo(infoId.value)
  infoData.value = res.data
  // console.log(InfoRef.value, '报警详情')
  InfoRef.value.loading = false
  // status==1开启刷新 用于组件刷新时传值调用
  if (status) {
    // 获取当前时间
    times.value = InfoRef.value.getCurrentTime(infoData.value.createdDate)
    start.value = new Date(times.value[0]).getTime()
    end.value = new Date(times.value[1]).getTime()
    getDetailList(1, start.value, end.value)
  }
}

const timeDown = ref(12) //倒计时
function switchChg(e) {
  if (e) {
    InfoRef.value.timeDis = true
    // 轮询请求获取数据
    timer = setInterval(() => {
      // 某些定时器操作
      timeDown.value--
      if (timeDown.value === 0) {
        timeDown.value = 12
        let start
        let end
        // 12s刷新一次
        start = Date.parse(new Date()) - 12000
        end = Date.parse(new Date())
        getDetailList(2, start, end)
      }
    }, 1000 * 1) // 1s * n
  } else {
    clearInterval(timer)
    timer = null
    InfoRef.value.timeDis = false
  }
}
const arrAllData = ref([])
const Seriesset = ref([])
const arrSeries = ref([])

// 设备详情
async function getDetailList(type, startTimes, endTimes) {
  // type 1.正常 2.开启实时
  try {
    let deviceId = infoData.value.deviceId
    let start
    let end
    start = startTimes
    end = endTimes
    if (type == 1) {
      InfoRef.value.deEchart.loading = true
    }
    let res = await Device.getDetail(deviceId, start, end)
    if (type == 1) {
      InfoRef.value.deEchart.loading = false
    }
    let newData
    if (res.data.length) {
      newData = JSON.parse(JSON.stringify(res.data))
      // console.log(bb, "bb");
      // 排序
      newData.sort(function (a, b) {
        return new Date(a.logDate).getTime() - new Date(b.logDate).getTime()
      })

      let rawdata = [
        {
          id: 1,
          name: infoData.value.type == 'oxygen' ? '氧气' : '可燃气 ',
          unit: infoData.value.type == 'oxygen' ? '%V/V' : '%LEL',

          type: 'line',
          data: [],
        },
      ]
      let arrSeries = [
        {
          name: infoData.value.type == 'oxygen' ? '氧气' : '可燃气 ',
          unit: infoData.value.type == 'oxygen' ? '%V/V' : '%LEL',
          type: 'line',
          showSymbol: false,
          smooth: true,
          data: [],
          // areaStyle: {
          //   normal: {
          //     //渐变色
          //     color: "#008c8c",
          //   },
          // },
        },
      ]
      for (let i = 0; i < newData.length; i++) {
        for (const key in rawdata) {
          if (rawdata.hasOwnProperty(key)) {
            const element = rawdata[key]
            element.data[element.data.length] = [newData[i].logDate, Number(newData[i].data.concentration)] //[1693808914737, 0]
          }
        }
      }
      if (type !== 2) {
        // InfoRef.value.$refs.deEchart.loading = false

        arrSeries.forEach((a, i) => {
          for (const arr of newData) {
            a.data.push({
              name: arr.logDate,
              value: [arr.logDate, arr.data.concentration],
            })
          }
        })
        arrAllData.value = arrSeries
        arrSeries.value = arrSeries
        // 只有普通请求的时候调用，实时刷新不调用
        InfoRef.value.setOptionsEchars(arrSeries.value)

        // console.log(arrAllData.value, ' 正常的this.arrAllData')
      } else {
        // 实时刷新开启
        let liveData = []
        arrSeries.forEach((a, i) => {
          for (const arr of newData) {
            a.data.push({
              name: arr.logDate,
              value: [arr.logDate, arr.data.concentration],
            })
          }
        })
        liveData = arrSeries
        // 合并数据
        liveData.forEach((el, ie) => {
          arrAllData.value.forEach((all, idx) => {
            if (el.name == all.name) {
              el.data.forEach(bl => {
                all.data.push(bl)
              })
            }
          })
        })

        Seriesset.value = arrAllData.value
        InfoRef.value.deEchart.liveOption(Seriesset.value)

        console.log(Seriesset.value, 'Seriesset')
      }
    } else {
      // InfoRef..value.$refs.deEchart.loading = false
      InfoRef.value.deEchart.loading = false
      $message.error('没有获取到数据')
    }
  } catch (error) {
    InfoRef.value.deEchart.loading = false

    console.log(error, 'error')
  }
}
provide('getDetailList', getDetailList) //前面是方法名，后面是方法，最好设置为一样
provide('getInfoList', getInfoList) //前面是方法名，后面是方法，最好设置为一样
onMounted(() => {
  infoId.value = route.query.id
  getInfoList(true)
})
let timer = null

function refresh() {
  timer = setInterval(() => {
    WarnList()
  }, 3000)
}
onBeforeUnmount(() => {
  clearInterval(timer)
  timer = null
})
</script>
<style lang="scss" scoped>
#InfoList {
  height: calc(100vh - 80px);
}
</style>
